package com.shengqi.xinnongren.work.ui.user.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

import butterknife.BindView;
import butterknife.OnClick;

import com.alipay.sdk.app.AuthTask;
import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpActivity;
import com.shengqi.xinnongren.common.config.user.UserManager;
import com.shengqi.xinnongren.common.utils.LogUtil;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.work.model.HttpRespond;
import com.shengqi.xinnongren.work.ui.home.activities.MainActivity;
import com.shengqi.xinnongren.work.ui.user.presenter.LoginPresenter;
import com.shengqi.xinnongren.work.ui.user.view.LoginView;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

/**
 * 登录
 */
public class LoginActivity extends BaseMvpActivity<LoginView, LoginPresenter> implements LoginView {

    private static final String TAG = "qqq";
    @BindView(R.id.edt_phone)
    EditText edt_phone;
    @BindView(R.id.edt_pwd)
    EditText edt_pwd;

    /**
     * 第三方登录唯一ID
     */
    private String mUid;
    /**
     * 第三方登录昵称
     */
    private String mName;
    /**
     * 第三方登录头像
     */
    private String mHeadUrl;

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        requestTranslucentStatusBar(Color.TRANSPARENT, false);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @OnClick(R.id.btn_login)
    void login() {
        String strPhone = edt_phone.getText().toString();
        if (TextUtils.isEmpty(strPhone)) {
            ToastHelper.getInstance(this).showWarn("请输入手机号");
            return;
        }
        String strPwd = edt_pwd.getText().toString();
        if (TextUtils.isEmpty(strPwd)) {
            ToastHelper.getInstance(this).showWarn("请输入密码");
            return;
        }
        mPresenter.doLogin(strPhone, strPwd);


    }

    @OnClick(R.id.tv_register)
    void register() {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    @OnClick(R.id.tv_forgetpwd)
    void forgetPwd() {
        startActivity(new Intent(this, ForgetPwdActivity.class));
    }

    @Override
    public void showLoadingView() {
        showLoadingDialog();
    }

    @Override
    public void hideLoadingView() {
        hideLoadingDialog();
    }

    @Override
    public void onNetworkError() {
        hideLoadingDialog();
    }

    @Override
    public void loginRes(HttpRespond respond) {
        UserManager.getInstance().saveIv(mPresenter.getIv());
        UserManager.getInstance().saveKey(mPresenter.getKey());
        UserManager.getInstance().saveLoginData(edt_phone.getText().toString(), mPresenter.getLocalToken());

        ToastHelper.getInstance(this).showSucceed("登录成功");
        startActivity(new Intent(this, MainActivity.class));
        finish();

    }

    @Override
    public void showRequestFailed(String message) {
        ToastHelper.getInstance(this).showWarn(message);
    }

    @Override
    public void showWeChatLoginRes(String data) {
        if (data.equals("0")) {
            //绑定手机号
            Bundle bundle = new Bundle();
            bundle.putString("uid", mUid);
            bundle.putString("name", mName);
            bundle.putString("headUrl", mHeadUrl);
            BindPhoneActivity.start(this, bundle, BindPhoneActivity.TYPE_WECHAT);
        } else {
            UserManager.getInstance().saveIv(mPresenter.getIv());
            UserManager.getInstance().saveKey(mPresenter.getKey());
            UserManager.getInstance().saveLoginData(edt_phone.getText().toString(), mPresenter.getLocalToken());

            ToastHelper.getInstance(this).showSucceed("登录成功");
            startActivity(new Intent(this, MainActivity.class));
        }
        finish();
    }

    /**
     * 支付宝登录回调信息
     *
     * @param data
     */
    @Override
    public void showALiLoginData(String data) {
        Runnable authRunnable = () -> {
            // 构造AuthTask 对象
            AuthTask authTask = new AuthTask(LoginActivity.this);
            // 调用授权接口，获取授权结果
            Map<String, String> result = authTask.authV2(data, true);

            Message msg = new Message();
            msg.what = 1;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @Override
    public void showALiLoginRes(String data) {
        if (data.equals("0")) {
            //绑定手机号
            Bundle bundle = new Bundle();
            bundle.putString("user_id", mUser_id);
            bundle.putString("auth_code", mAuth_code);
            BindPhoneActivity.start(this, bundle, BindPhoneActivity.TYPE_ALI);
        } else {
            UserManager.getInstance().saveIv(mPresenter.getIv());
            UserManager.getInstance().saveKey(mPresenter.getKey());
            UserManager.getInstance().saveLoginData(edt_phone.getText().toString(), mPresenter.getLocalToken());

            ToastHelper.getInstance(this).showSucceed("登录成功");
            startActivity(new Intent(this, MainActivity.class));
        }
        finish();
    }

    private String mUser_id;
    private String mAuth_code;
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                //{resultStatus=9000, result=   success=true&result_code=200&app_id=2018090561232445&auth_code=30e4968cb51841d9a497173d3b17QX81&scope=kuaijie&alipay_open_id=20880005246861801861831681715681&user_id=2088022394111814   , memo=}
                Map<String, String> map = (Map<String, String>) msg.obj;
                String result = map.get("result");
                if (result.contains("auth_code") && result.contains("user_id")) {
                    mUser_id = result.substring(result.indexOf("user_id") + 8, result.indexOf("user_id") + 8 + 16);
                    mAuth_code = result.substring(result.indexOf("auth_code") + 10, result.indexOf("auth_code") + 10 + 32);
                    mPresenter.ALiLogin(mUser_id, mAuth_code);
                }
            }
        }
    };

    /**
     * 微信登录
     */
    @OnClick(R.id.iv_wechat_login)
    void wechatLogin() {
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);
        UMShareAPI mShareAPI = UMShareAPI.get(this);
        mShareAPI.getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener);
    }

    /**
     * 支付宝登录
     */
    @OnClick(R.id.iv_ali_login)
    void ALiLogin() {
        mPresenter.getALiLoginData();
    }


    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            Log.e(TAG, "onStart: ");
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            mUid = data.get("uid");
            mName = data.get("name");
//            String gender = data.get("gender");
            mHeadUrl = data.get("iconurl");

            mPresenter.WeChatLogin(mUid, mName, mHeadUrl);
            LogUtil.e("用户信息: " + data.toString());
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            LogUtil.e("授权登录失败：" + t.getMessage());
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            ToastHelper.getInstance(LoginActivity.this).showWarn("取消授权");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
